//
//  HGPlaceOderVC.m
//  RedWinMall
//
//  Created by HeDianZhao on 2018/8/4.
//  Copyright © 2018年 HeDianZhao. All rights reserved.
//

#import "HGPlaceOderVC.h"
#import "HGGoodsModel.h"
#import "HGOrderCell.h"
#import "HGAddressModel.h"
#import "HGOrderCenterVC.h"
#import "HGSeletedView.h"
#import "PayViewModel.h"


@interface HGPlaceOderVC ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic,strong)UITableView* tableView;

@property (nonatomic,strong)UIView* bottomView;

@property (nonatomic,strong)UILabel *moenyCount;

@property (strong, nonatomic) HGSeletedView *seletedView;

@end

@implementation HGPlaceOderVC {
    NSInteger defaultCount;
    NSInteger _payType;//支付方式1.支付宝 2.微信
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initSubViews];
}

- (void)initSubViews {
    
    _payType = 2;
    
    self.title = @"确认下单";
    
    defaultCount = _model.userChooseCount;
    
    [self.tableView registerClass:[HGOrderCell class] forCellReuseIdentifier:@"HGOrderCell"];
    [self.tableView registerClass:[HGOrderAddressCell class] forCellReuseIdentifier:@"HGOrderAddressCell"];
    [self.tableView registerClass:[HGOrderGoodsCell class] forCellReuseIdentifier:@"HGOrderGoodsCell"];
    [self.tableView registerClass:[HGGoodsInfoCell class] forCellReuseIdentifier:@"HGGoodsInfoCell"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveCount:) name:@"cumulative" object:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucess:) name:kAliPayScuess object:nil];
    
    WS(weakSelf)
    _seletedView = [HGSeletedView shareSeletedView];
    _seletedView.callDisbtuion = ^(NSInteger row) {
        weakSelf.model.userChooseType = row;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        //2.将indexPath添加到数组
        NSArray <NSIndexPath *> *indexPathArray = @[indexPath];
        //3.传入数组，对当前cell进行刷新
        [weakSelf.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    
    _seletedView.callBack = ^(HGAddressModel *model) {
        _addressModel = model;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        //2.将indexPath添加到数组
        NSArray <NSIndexPath *> *indexPathArray = @[indexPath];
        //3.传入数组，对当前cell进行刷新
        [weakSelf.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    [self.view addSubview:_seletedView];
}

#pragma mark - 支付成功做的操作
- (void)paySucess:(NSNotification *)dict {
    
    NSString *payNo = @"";
    if ([dict.userInfo[@"pay"] isEqualToString:@"weixin"]) {
        payNo = [[NSUserDefaults standardUserDefaults] objectForKey:@"oderNo"];
    } else {
        payNo = dict.userInfo[@"payNo"];
        NSData *jsonData = [payNo dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        payNo = dic[@"alipay_trade_app_pay_response"][@"out_trade_no"];
    }
    
    NSString *oderNo = [[NSUserDefaults standardUserDefaults] objectForKey:@"oderNo"];
    
   
    
    NSDictionary *parameters = @{
                                 @"orderNo" : oderNo,
                                 @"payNo" : payNo
                                 };
    [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/order/pay/success") parameters:parameters completion:^(LMJBaseResponse *response) {
        if (response.responseModel.status == 1) {
            HGOrderCenterVC *vc = [[HGOrderCenterVC alloc] init];
            vc.type = 2;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
}

#pragma mark - 选择多少个数
- (void)receiveCount:(NSNotification *)center {
    _model.userChooseCount = [center.userInfo[@"count"] integerValue];
    [_tableView reloadData];
    _moenyCount.text = [NSString stringWithFormat:@"应付：￥%.2lf",_model.userChooseCount * [_model.rate floatValue]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        HGOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGOrderCell"];
        cell.type = _model.userChooseType;
        return cell;
    } else if (indexPath.row == 1) {
        HGOrderAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGOrderAddressCell"];
        cell.model = _addressModel;
        cell.type = 2;
        return cell;
    } else if (indexPath.row == 2) {
        HGOrderGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGOrderGoodsCell"];
        cell.model = _model;
        return cell;
    } else {
        HGGoodsInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGGoodsInfoCell"];
        cell.model = _model;
        cell.callBack = ^(NSInteger payType) {
            _payType = payType;
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 45;
    } else {
        return indexPath.row == 1 ? 62 : indexPath.row == 3 ? 250 : 110;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= 2) return;
    
    _seletedView.isFoodView = YES;
    _seletedView.titleLabel.text = @"配送方式";
    if (indexPath.row == 0) {
        _seletedView.addressModels = @[];
        _seletedView.distribution = @[@"自提",@"平邮",@"快递"];
    } else {
        _seletedView.distribution = @[];
        [[XNProgressHUD shared] showLoadingWithTitle:@"加载中" maskType:(XNProgressHUDMaskTypeBlack)];
        _seletedView.isFoodView = _model.userChooseType == 2 ? YES : NO;
        _seletedView.titleLabel.text = _model.userChooseType == 2 ? @"自提地址" : @"收货地址";
        NSString *url = _model.userChooseType == 2 ? @"app/user/address/selflift/list" : @"app/user/address/list";
        [[LMJRequestManager sharedManager] GET:KBaseURL(url) parameters:nil completion:^(LMJBaseResponse *response) {
            [[XNProgressHUD shared] dismiss];
            if (response.responseModel.status == 1) {
                _seletedView.addressModels = [HGAddressModel mj_objectArrayWithKeyValuesArray:response.responseModel.data];
            } else {
                _seletedView.addressModels = @[];
            }
        }];
    }
    [_seletedView begain];
}

#pragma mark - 确认下单
- (void)submit {
    
    [[XNProgressHUD shared] showLoadingWithTitle:@" 加载中" maskType:(XNProgressHUDMaskTypeBlack)];
    ///1. 支付宝 2. 微信
    NSDictionary *parameters = @{
                                 @"sendType" : @(_model.userChooseType).description,
                                 @"receivePerson" : _addressModel.receivePerson,
                                 @"receiveTell" : _addressModel.receiveTell,
                                 @"receiveAddress" : [NSString stringWithFormat:@"%@%@%@%@",_addressModel.province,_addressModel.city,_addressModel.area,_addressModel.detail],
                                 @"productId" : @(_model.goodsId).description,
                                 @"num" : @(_model.userChooseCount).description,
                                 @"orderAmount" : _model.rate,
                                 @"payAmount" : @(_model.userChooseCount * [_model.rate floatValue]).description
                                 };
    
    [[LMJRequestManager sharedManager] POST:KBaseURL(@"app/order/create") parameters:parameters completion:^(LMJBaseResponse *response) {
        if (response.responseModel.status == 1) {
            [self loadPayData:response.responseModel.data];
        }
    }];
    
}

- (void)loadPayData:(NSString *)oder {
    
    [[NSUserDefaults standardUserDefaults] setValue:oder forKey:@"oderNo"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/order/pay/param") parameters:@{@"orderNo" : oder,@"payWay" : [NSNumber numberWithInteger:_payType]} completion:^(LMJBaseResponse *response) {
        [[XNProgressHUD shared] dismiss];
        if (response.responseModel.status == 1) {
            
            if (_payType == 1) {
                [[PayViewModel sharePayService] AliPayWithSignature:response.responseModel.data[@"param"]];
                return;
            }
            NSData *jsonData = [response.responseModel.data[@"param"] dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *param = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
            PayModel *model = [PayModel new];
            [model setValuesForKeysWithDictionary:param];
            [[PayViewModel sharePayService] WeChatWithModel:model];
        }
    }];
}

- (UITableView *)tableView {
    if (!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.bottom.equalTo(self.bottomView.mas_top);
        }];
    }
    return _tableView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_bottomView];
        
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.offset(49 + kTabbarSafeBottomMargin);
        }];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = kColorBackground;
        lineView.layer.shadowColor = kColorBackground.CGColor;
        [_bottomView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(_bottomView);
            make.height.offset(1);
        }];
        
        UIButton *fkButton = [[UIButton alloc] init];
        [fkButton setTitle:@"去付款" forState:(UIControlStateNormal)];
        [fkButton setBackgroundColor:kColorMainTheme];
        fkButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [fkButton addTarget:self action:@selector(submit) forControlEvents:(UIControlEventTouchUpInside)];
        [_bottomView addSubview:fkButton];
        
        [fkButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.bottom.equalTo(_bottomView);
            make.width.equalTo(_bottomView).multipliedBy(0.3);
        }];
        
        _moenyCount = [[UILabel alloc] init];
        _moenyCount.text = [NSString stringWithFormat:@"应付：￥%.2lf",_model.userChooseCount * [_model.rate floatValue]];
        _moenyCount.textColor = kColorMainTheme;
        _moenyCount.font = [UIFont systemFontOfSize:20];
        [Utility fuwenbenLabel:_moenyCount fontNumber:[UIFont systemFontOfSize:14] andRange:NSMakeRange(0, 3) andColor:kColorDefult];
        [_bottomView addSubview:_moenyCount];
        [_moenyCount mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(14);
            make.top.bottom.equalTo(_bottomView);
            make.right.equalTo(fkButton.mas_left);
        }];
        
    }
    return _bottomView;
}

- (void)dealloc {
    _model.userChooseCount = defaultCount;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"receiveCount" object:nil];
}

@end
